<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.agentId"
          type="number"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
          class="filter-item"
          placeholder="请输入Id"
        ></el-input>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.userName"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
          class="filter-item"
          placeholder="请输入名称"
        ></el-input>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.userAccount"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
          class="filter-item"
          placeholder="请输入账号"
        ></el-input>

        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.userPhone"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
          class="filter-item"
          placeholder="请输入手机号"
        ></el-input>

        <el-select
          v-model="listQuery.agentType"
          placeholder="请选择角色"
          clearable
          class="filter-item"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
        >
          <el-option
            v-for="item in status"
            :key="item.status"
            :label="item.desc"
            :value="item.status"
          ></el-option>
        </el-select>
        <el-input
          @keyup.enter.native="handleFilter"
          clearable
          v-model="listQuery.address"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
          class="filter-item"
          placeholder="请输入地址"
        ></el-input>
        <el-select
          v-model="listQuery.isFlag"
          placeholder="请选择状态"
          clearable
          class="filter-item"
          style="width: 200px; margin-right: 15px; margin-top: 7px"
        >
          <el-option
            v-for="item in isFlagdata"
            :key="item.status"
            :label="item.desc"
            :value="item.status"
          ></el-option>
        </el-select>
        <!-- 2022.09.07  合并为时间日期选择器 -->
        <el-date-picker
          v-model="dateTime"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:00"
          @change="getDateTime"
        >
        </el-date-picker>
        <!-- <el-date-picker v-model="listQuery.startTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 200px;margin-right:15px;margin-top:7px"

                          placeholder="选择开始日期"></el-date-picker>
          <el-date-picker v-model="listQuery.endTime"
         type="datetime"
         style="width: 200px;margin-right:15px;margin-top:7px"
         value-format="yyyy-MM-dd HH:mm:ss"
         placeholder="选择结束日期"></el-date-picker> -->

        <br />
        <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-search"
          @click="handleFilter"
          style="width: 80px; margin-right: 15px; margin-top: 7px"
          >搜索</el-button
        >
        <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-circle-plus-outline"
          @click="beforOpenDialog(1)"
          style="width: 120px; margin-right: 15px; margin-top: 7px"
          >添加渠道商</el-button
        >
        <el-button
          style="width: 80px; margin-right: 15px; margin-top: 7px"
          type="primary"
          class="filter-item"
          @click="handleDownload"
          icon="el-icon-download"
          :loading="downloadLoading"
          >导出</el-button
        >
      </el-form>
    </div>
    <!-- table 表格 -->
    <el-table
      :data="list"
      v-loading="loading.list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="序号" prop="index" align="center" width="80px" />
      <!-- <el-table-column label="Id" prop="agentId" align="center" /> -->
      <el-table-column label="名称" prop="userName" align="center" />
      <el-table-column label="账号" prop="userAccount" align="center" />
      <el-table-column label="手机号" prop="userPhone" align="center" />
      <el-table-column label="角色" prop="agentTypeInfo" align="center" />
      <el-table-column label="地址" prop="address" align="center" />
      <el-table-column
        label="收益金额(元)"
        sortable
        prop="amountInfo"
        align="center"
      />
      <el-table-column
        label="物业每度电的费用(元)"
        width="170"
        sortable
        prop="electricityAmountInfo"
        align="center"
      />
      <!-- <el-table-column label="比例" prop="ratioInfo" align="center" /> -->
      <el-table-column label="状态" prop="isFlagInfo" align="center" />
      <el-table-column label="所属群组" prop="superiorId" align="center" />
      <el-table-column label="创建时间" sortable prop="ctime" align="center" />
      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-open"
            @click="updateBackAgentIsFlag(scope.row.agentId, 1)"
            v-if="scope.row.isFlag === 2"
            type="primary"
            class="Bot-bt"
            >启用</el-button
          >
          <el-button
            icon="el-icon-turn-off"
            type="warning"
            @click="updateBackAgentIsFlag(scope.row.agentId, 2)"
            v-else
            class="Bot-bt"
            >禁用</el-button
          >
          <el-button
            icon="el-icon-open"
            @click="beforOpenDialog(2, scope.row)"
            type="primary"
            class="Bot-bt"
            >编辑</el-button
          >
          <el-button
            icon="el-icon-open"
            @click="updateBackAgentPassword(scope.row.agentId)"
            type="primary"
            class="Bot-bt"
            >重置密码</el-button
          >
          <!-- <el-button
            icon="el-icon-open"
            @click="detele(scope.row.agentId)"
            type="danger" class="Bot-bt"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.offset"
        :page-sizes="[10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 添加代理商弹窗 -->
    <el-dialog :title="diglogTitle" :visible.sync="dialog.add">
      <el-form
        :model="addQuery"
        :rules="bindRules"
        ref="bindForm"
        label-position="right"
        label-width="120px"
        style="textalign: center"
      >
        <el-form-item label="账号" prop="userAccount">
          <el-input
            maxlength="20"
            :disabled="this.dialogType === 2"
            clearable
            v-model="addQuery.userAccount"
            placeholder="请输入账号(6-20个字符,不包含空格,不能包含中文!)"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="this.dialogType === 1" label="密码" prop="passWord">
          <el-input
            type="password"
            maxlength="20"
            clearable
            v-model="addQuery.passWord"
            placeholder="请输入密码(6-20个字符,不包含空格,不能包含中文,必须包含数字,字母或字符至少两种！)"
          ></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="userName">
          <el-input
            maxlength="15"
            clearable
            v-model="addQuery.userName"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="userPhone">
          <el-input
            clearable
            maxlength="11"
            v-model="addQuery.userPhone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item  label="代理商角色" prop="agentType">
          <el-select
          :disabled="this.dialogType === 2"
            v-model="addQuery.agentType"
            placeholder="请选择代理商角色"
            clearable
            class="filter-item"
            style="width: 200px;"
          >
            <el-option label="省级全资子公司" :value=1></el-option>
            <el-option label="省级政府" :value=4></el-option>
          </el-select>
        </el-form-item> -->

        <!-- 省市选择 -->

        <!-- <el-form-item v-if="addQuery.agentType === 2" label="所在地区" required>
        <pcq
          :proviceId.sync="addQuery.province"
          :cityId.sync="addQuery.city"
          :areaId.sync="addQuery.area"
        ></pcq>
      </el-form-item> -->

        <el-form-item label="所在地区">
          <el-form-item style="display: inline-block">
            <el-select
              :disabled="this.dialogType === 2"
              clearable
              style="width: 100px"
              v-model="addQuery.province"
              placeholder="省"
              class="filter-item"
              @change="getCities2(1)"
            >
              <el-option
                v-for="p in provices"
                :label="p.NAME"
                :value="p.AREA_ID"
                :key="p.AREA_ID"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="city" style="display:inline-block">
          <el-select
            :disabled="this.dialogType === 2"
            clearable
            style="width: 100px;"
            v-model="addQuery.city"
            placeholder="市"
            class="filter-item"
            @change="getAreas2(1)"
          >
            <el-option v-for="c in cities" :label="c.NAME" :value="c.AREA_ID" :key="c.AREA_ID"/>
          </el-select>
        </el-form-item> -->
          <!-- <el-form-item prop="area" style="display:inline-block">
          <el-select
            clearable
            style="width: 120px;"
            v-model="addQuery.area"
            placeholder="区"
            class="filter-item"
          >
            <el-option v-for="a in areas" :label="a.NAME" :value="a.AREA_ID" :key="a.AREA_ID"/>
          </el-select>
        </el-form-item> -->
        </el-form-item>
        <!-- <el-form-item  v-if="addQuery.agentType === 1" label="比例" prop="ratio">
          <el-input maxlength="3" clearable v-model="addQuery.ratio" placeholder="请输入比例（比例范围0-100）"></el-input>
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!-- 角色分配 -->
    <!-- <el-dialog
      title="角色分配"
      :visible.sync="roleShow"
      @close="closeDialog"
      width="50%"
      v-loading="loading"
    >
      <el-form :model="roleForm">
        <el-form-item
          prop="name"
          label="角色节点"
          :label-width="formLabelWidth"
        >
          <div style="margin-right: 20px">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
          </div>
          <el-checkbox-group
            v-model="roleCheck"
            @change="handleCheckedRoleChange"
          >
            <el-checkbox
              v-for="(item, index) in roleData"
              :key="index"
              :value="item.id"
              :label="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="roleAllocation()">分配角色</el-button>
      </div>
    </el-dialog> -->

    <!-- 回到顶部 -->
    <BackToTop></BackToTop>
  </div>
</template>
<script>
import {
  getAddressByAreaId,
  getId,
  getAddress,
  getObjByName,
  getObjByAreaId,
  getByNameProvinceId,
  getByNameCityId,
  getByNameAreaId,
} from "@/utils/getAddress";
import {
  list,
  addBackAgent,
  updateBackAgentIsFlag,
  updateBackAgentPassword,
  del,
  updateBackAgent,
} from "@/api/adminEnt";
import { createManager } from "@/api/managerList";
import pcq from "@/components/index";
import BackToTop from "@/components/BackToTop";
import VePie from "v-charts/lib/pie";
import Velocity from "velocity-animate";
import "velocity-animate/velocity.ui.js";
import { parseTime } from "@/utils";
export default {
  name: "equipment_list",
  components: {
    BackToTop,
    VePie,
    pcq,
  },

  data() {
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空!"));
      }
      setTimeout(() => {
        var num = Number(value);
        if (!Number.isInteger(num)) {
          callback(new Error("请输入数字!"));
        } else {
          if (num < 0) {
            callback(new Error("请输入正整数!"));
          }
          if (!/^1[3456789]\d{9}$/.test(num)) {
            callback(new Error("手机号码有误，请重填!"));
          }
          callback();
        }
      }, 300);
    };

    var validateUserAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账号不能为空!"));
      }
      setTimeout(() => {
        var isNum = /(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{5,19}$/;
        if (!isNum.test(value)) {
          callback(new Error("6-20个字符,不包含空格,不能包含中文!"));
        }
        callback();
      }, 300);
    };

    var validatePassWord = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空!"));
      }
      setTimeout(() => {
        var isNum =
          /(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{5,19}$/;
        if (!isNum.test(value)) {
          callback(
            new Error(
              "6-20个字符,不包含空格,不能包含中文,必须包含数字,字母或字符至少两种!"
            )
          );
        }
        callback();
      }, 300);
    };

    var validateRatio = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("比例不能为空!"));
      }
      setTimeout(() => {
        var isNum = /^([1]?\d{1,2})$/;
        // console.log(isNum.test(value))
        if (!isNum.test(value)) {
          callback(new Error("请输入整数,比例范围0-100!!"));
        }
        callback();
      }, 300);
    };
    return {
      dateTime: "",
      provices: [],
      cities: [],
      areas: [],
      pId: "",
      cId: "",
      // 搜索/返回数据
      dialogType: "",
      listQuery: {
        offset: 1,
        limit: 10,
        agentId: "",
        userName: "",
        userPhone: "",
        agentType: "",
        address: "",
        startTime: "",
        endTime: "",
        userAccount: "",
        isFlag: "",
        // 接收部分数据
      },
      // 新建代理商数据
      addQuery: {
        agentId: "",
        userAccount: "",
        passWord: "",
        userName: "",
        userPhone: "",
        agentType: "",
        ratio: "",
        province: "",
        city: "",
      },

      chartData: null,
      loading: {
        list: false,
        add: false,
        detele: false,
        upd: false,
      },
      dialog: {
        bind: false,
        add: false,
        upd: false,
        view: false,
      },
      imgList: [],
      total: 0,
      downloadLoading: false,
      date: "",
      bindRules: {
        userAccount: [
          { required: true, validator: validateUserAccount, trigger: "blur" },
        ],
        passWord: [
          { required: true, validator: validatePassWord, trigger: "blur" },
        ],
        userName: [{ required: true, message: "请输入名称", trigger: "blur" }],

        userPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        agentType: [
          { required: true, message: "请输入选择类型", trigger: "blur" },
        ],
        ratio: [{ required: true, validator: validateRatio, trigger: "blur" }],
        // province: [
        //   { required: true, message: "请选择省", trigger: "blur" }
        // ],
      },
      status: [
        { status: 1, desc: "省级全资子公司" },
        { status: 2, desc: "公司子级账号" },
        { status: 3, desc: "物业" },
        { status: 4, desc: "省级政府" },
      ],
      isFlagdata: [
        { status: 1, desc: "启用" },
        { status: 2, desc: "禁用" },
      ],

      list: null,
      chargeRules: [],
      downloadLoading: false,
      equipmentCount: 0,
      showPic: "",
      dialogVisible: false,
    };
  },

  methods: {
    getDateTime(value) {
      if (value) {
        this.listQuery.startTime = value[0];
        this.listQuery.endTime = value[1];
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },
    //导出
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "序号",
          "Id",
          "名称",
          "账号",
          "手机号",
          "角色",
          "地址",
          "收益金额(元)",
          "物业每度电的费用(元)",
          "状态",
          "上级Id",
          "创建时间",
        ];
        const filterVal = [
          "index",
          "agentId",
          "userName",
          "userAccount",
          "userPhone",
          "agentTypeInfo",
          "address",
          "amountInfo",
          "electricityAmountInfo",
          "isFlagInfo",
          "superiorId",
          "ctime",
        ];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "代理商列表",
        });
        this.downloadLoading = false;
      });
    },
    // 数据筛选
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },

    //文件导入
    async importEquipments(e) {
      const fd = new FormData();
      fd.append("file", e.target.files[0]);
      //调用服务器接口
      const res = await importExcelEquipment(fd);
      if (res.code == 1) {
        this.$message({
          type: "success",
          message: "正在新增设备请稍候刷新页面...!",
        });
        this.lists();
        //this.equipmentList();
      } else {
        this.$message({
          type: "error",
          message: res.msg,
        });
      }
    },

    // 获取代理商列表
    async lists() {
      this.loading.list = true;
      try {
        //调用服务器接口
        const { data } = await list({
          ...this.listQuery,
        });
        this.list = data.records.map((item, index) => ({
          index: index + 1,
          amountInfo: item.agentType == 1 ? item.amount / 100 : "-",
          electricityAmountInfo:
            item.agentType == 3 ? item.electricityAmount / 100 : "-",
          agentTypeInfo:
            item.agentType == 0
              ? "超级管理员"
              : item.agentType == 1
              ? "一级管理员"
              : item.agentType == 2
              ? "二级管理员"
              : item.agentType == 3
              ? "三级管理员"
              : "-",
          ratioInfo: item.agentType == 1 ? item.ratio : "-",
          isFlagInfo:
            item.isFlag == 1 ? "启用" : item.isFlag == 2 ? "禁用" : "",
          address:
            (item.province ? item.province : "") +
            (item.city ? item.city : "") +
            (item.area ? item.area : "") +
            (item.district ? item.district : ""),
          ...item,
        }));
        this.total = data.total;
      } catch (error) {}
      this.loading.list = false;
    },

    //添加代理商
    async add() {
      this.$refs["bindForm"].validate(async (valid) => {
        if (valid) {
          try {
            let query = {
              agentId: this.addQuery.agentId,
              userAcount: this.addQuery.userAccount,
              passWord: this.addQuery.passWord,
              userName: this.addQuery.userName,
              userPhone: this.addQuery.userPhone,
              // agentType: this.addQuery.agentType,
              province: getAddress(this.addQuery.province),
              // ratio: this.addQuery.ratio,
            };
            this.loading.add = true;
            if (this.dialogType === 1) {
              //调用服务器接口
              const { data } = await createManager(query);
            } else {
              //调用服务器接口
              const { data } = await updateBackAgent(query);
            }
            this.$message({
              type: "success",
              message: "操作成功",
            });
            this.dialog.add = false;
            this.loading.add = false;
            this.resetForm();
            this.lists();
          } catch (error) {
            this.loading.add = false;
            //  this.resetForm()
          }
        }
      });
    },

    resetForm(flag) {
      this.$refs.bindForm && this.$refs.bindForm.resetFields();
      if (flag) {
        this.addQuery = {
          id: "",
        };
      }
    },
    beforOpenDialog(type, item) {
      if (type === 1) {
        this.resetForm(1);
      } else {
        this.resetForm();
        const {
          agentId,
          userAccount,
          passWord,
          userName,
          userPhone,
          agentType,
          ratio,
          province,
        } = item;
        this.addQuery = {
          ...this.addQuery,
          agentId,
          userAccount,
          passWord,
          userName,
          userPhone,
          agentType,
          ratio,
          province,
        };
        if (this.addQuery.agentType === 2) {
          this.addQuery.province = getByNameProvinceId(province);
          this.getCities2();
          this.getAreas2();
        }
      }
      this.dialogType = type;
      this.dialog.add = true;
    },

    //删除
    detele(agentId) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          //调用服务器接口
          const { data } = await del({ agentId });
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.lists();
        } catch (error) {}
      });
    },

    //修改状态
    updateBackAgentIsFlag(agentId, isFlag) {
      const msg = isFlag === 1 ? "确定启用?" : "确定禁用?";
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          //调用服务器接口
          const { data } = await updateBackAgentIsFlag({
            agentId: agentId,
            isFlag: isFlag,
          });
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.lists();
        } catch (error) {}
      });
    },
    //重置密码
    updateBackAgentPassword(agentId) {
      this.$confirm("确定重置该账号密码为：a123456", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          //调用服务器接口
          const { data } = await updateBackAgentPassword({ agentId });
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.lists();
        } catch (error) {}
      });
    },
    // 批量下载设备二维码
    downloadZipQr() {
      window.location.href =
        this.$uploadUrl + "api/equipment/admin/downloadZipQr";
    },

    handleFilter() {
      this.listQuery.offset = 1;
      this.lists();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.lists();
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val;
      this.lists();
    },
    //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId(fid) {
      return getAddressByAreaId(fid);
    },
    // 获取对应市
    getCities2(type) {
      if (type) {
        this.addQuery.city = "";
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.province;
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas2(type) {
      if (type) {
        this.addQuery.area = "";
      }
      this.pId = this.addQuery.city;
      this.areas = getAddressByAreaId(this.pId);
    },
    // 获取对应市Id
    getCities() {
      this.addQuery.area = "";
      this.areas = [];
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas() {
      this.addQuery.area = "";
      this.areas = getAddressByAreaId(this.cId);
    },
  },
  created() {
    (this.provices = getAddressByAreaId(0)), this.getCities();
    this.getAreas();
    this.lists();
    // console.log("role----",this.$store.state.user.userInfo.managerId);
  },

  computed: {
    diglogTitle() {
      return this.dialogType === 1 ? "新增代理商" : "编辑代理商";
    },
  },
};
</script>
<style lang="scss" scoped>
.el-button + .el-button {
  margin-left: 0px;
}
.Bot-bt {
  margin-bottom: 8px;
}
</style>
